package cn.b.sky.form.form.builder.impl;

import cn.b.sky.form.form.builder.BaseElementBuilder;
import cn.b.sky.form.model.BusinessField;
import cn.b.sky.form.model.ScreenField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

public class RadioBuilder extends BaseElementBuilder {

  @Override
  public String buildHtmlElement(ScreenField sf) {
    BusinessField field = sf.getBf();
    StringBuilder sb = new StringBuilder();
    List<Map<String, Object>> keyValues = this.getKeyValues(field);
    if(!CollectionUtils.isEmpty(keyValues)){
      int itemCount = keyValues.size();
      // 计算每个Item的宽度
      int width = FIELD_DIV_WIDTH / itemCount;
      for(int i = 0; i < itemCount; i++){
        Map<String, Object> item = keyValues.get(i);
        // 是
        sb.append("<label style=\"width:").append(width).append("px;\">");
        sb.append("<input type=\"radio\"");
        if (sf.getReadonlyFlag() == 1) {
          sb.append(" disabled=\"disabled\"");
        }
        if (!StringUtils.isBlank(field.getDbField()) && sf.getReadonlyFlag() != 1) {
          //sb.append(" id=\"").append(field.getDbField()).append("\"");
          sb.append("name=\"").append(field.getDbField()).append("\"");;
        }
        //输入框检验
        String validation = this.getValidationAttribute(field);
        if (!StringUtils.isBlank(validation)) {
          sb.append(" class=\"").append(validation).append("\"");
        }
        sb.append(" value=\"").append(item.get(SELECTVALUE)).append("\"");
        if(item.get(SELECTVALUE).equals(field.getDefaultValue())){
          sb.append(" checked=\"checked\"");
        }
        sb.append(" />");
        sb.append(item.get(SHOWITEM));
        sb.append("</label>");
      }
    }
    return sb.toString();
  }

}
